﻿using System;
using Irony.Ast;
using Irony.Parsing;
using LibraryGuard.Interfaces;

namespace LibraryGuard.Internals.AST
{
	/// <summary>
	/// Represents function call.
	/// </summary>
	internal class FunctionCall
		: IValue
	{
		#region Fields
		public readonly string Name = string.Empty;
		private readonly ParameterList Parameters = null;
		#endregion

		#region Constructors
		public FunctionCall(string name, ParameterList args)
		{
			this.Name = name;
			this.Parameters = args;
		}
		#endregion

		#region IValue Members
		/// <inheritdoc />
		public TypeCode GetBaseType(IDataProvider data)
		{
			return data.GetFunctionReturnType(this.Name);
		}

		/// <inheritdoc />
		public bool CanBeConvertedTo(TypeCode type, IDataProvider data)
		{
			return data.CallFunction(this.Name, this.Parameters.Parameters).CanBeConvertedTo(type, data);
		}

		/// <inheritdoc />
		public object GetValue(TypeCode type, IDataProvider data)
		{
			return data.CallFunction(this.Name, this.Parameters.Parameters).GetValue(type, data);
		}
		#endregion

		#region Statics
		public static void Create(AstContext context, ParseTreeNode parseNode)
		{
			parseNode.AstNode = new FunctionCall(parseNode.ChildNodes[0].Token.Text, (ParameterList)parseNode.ChildNodes[1].AstNode);
		}
		#endregion
	}
}
